import axios from 'axios'
import { Message } from 'element-ui'
import { getToken, clearUserCache } from '@/utils/myAuth'
import router from '@/router'

// create an axios instance
// process.env 指的是当前的运行环境 所对应的 配置文件
const service = axios.create({
    // baseURL: "http://leju.bufan.cloud", // url = base url + request url
    // withCredentials: true // 跨域携带cookies需要,token认证不需要
    timeout: 5000 // 请求超时时间
})

// request interceptor
service.interceptors.request.use(
    config => {
    // do something before request is sent
    // 如果本地有token  携带过去
        var token = getToken()
        if (token) {
            config.headers['token'] = token
        }
        return config
    },
    error => {
        // do something with request error
        console.log(error) // for debug
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        const res = response.data
        // token无效 会返回20002
        if (res.code === 20002) {
            Message({
                message: res.message + ',请重新登陆!',
                type: 'error',
                duration: 5 * 1000
            })
            // 清除用户缓存
            clearUserCache()
            router.push('/login')
            return null
        }

        return res
    },
    error => {
        console.log('err' + error) // for debug
        Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
        })
        return Promise.reject(error)
    }
)
/**
 * 合并get与post提交
 * @param {} config
 */
function http(config) {
    // 动手脚
    const axiosConfig = {
        url: config.url,
        method: config.method
    }
    // 如果data存在 而且不为空对象
    if (config.data) {
        if (Object.keys(config.data).length > 0) {
            console.log('hh')
            var key = config.method.toLowerCase() === 'get' ? 'params' : 'data'
            axiosConfig[key] = config.data
        }
        if (config.data.constructor === FormData) {
            console.log('sss')
            axiosConfig.data = config.data
        }
    }

    if (config.headers) {
        console.log('headrer')
        axiosConfig.headers = config.headers
    }
    return service(axiosConfig)
}
export default http
